package com.pdd.rocketmq.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author:liyangpeng
 * @date:2020/8/24 11:20
 */
@RestController
@RequestMapping("/rocket")
@Slf4j
public class RocketMQController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/sendMessage")
    public String sendMessage(String content){
        try {
            Map<String,Object> headers=new HashMap<>();
            headers.put(RocketMQHeaders.KEYS,UUID.randomUUID().toString());
            Message<String> message=new Message<String>() {
                @Override
                public String getPayload() {
                    return content;
                }
                @Override
                public MessageHeaders getHeaders() {
                    MessageHeaders messageHeaders=new MessageHeaders(headers);
                    return messageHeaders;
                }
            };
            rocketMQTemplate.asyncSend("pdd-topic-1:TagA", message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {

                }

                @Override
                public void onException(Throwable throwable) {

                }
            });
            SendResult sendResult = rocketMQTemplate.syncSend("pdd-topic-1:TagA", message);
            log.info("消息发送成功:{}",sendResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
